// 添加新节点
class Link {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}

// 初始化链表
class LinkList {
  constructor(val) {
    // 设置头结点
    this.head = new Link(val);
  }

  // 查找节点
  find(val) {
    let curNode = this.head;

    while (curNode && curNode.val) {
      if (curNode.val === val) {
        return curNode
      }

      curNode = curNode.next;
    }
    return null;
  }

  // 查找父节点
  findParent(val) {
    let curNode = this.head;

    while (curNode && curNode.next) {
      if (curNode.next.val === val) {
        return curNode;
      }

      curNode = curNode.next;
    }

    return null;
  }

  // 链表尾部添加节点
  add(val) {
    const newNode = new Link(val);
    let curNode = this.head;

    while (curNode.next) {
      curNode = curNode.next;
    }

    curNode.next = newNode;
  }

  // 插入节点
  insert(oldVal, newVal) {
    const newNode = new Link(newVal);
    let curNode = this.find(oldVal);

    if (!curNode) {
      throw `${oldVal}节点不存在`;
    }

    if (curNode.next) {
      newNode.next = curNode.next;
      curNode.next = newNode;
    } else {
      newNode.next = null;
      curNode.next = newNode;
    }

  }

  // 删除节点
  remove(val) {
    const delNode = this.find(val);

    if (!delNode) {
      throw `${delNode}节点不存在`;
    }

    const parentNode = this.findParent(delNode.val);

    if (delNode.next == null) {
      parentNode.next = null;
    } else {
      parentNode.next = delNode.next;
    }
  }

  // 修改节点
  change(val) {
    let curNode = this.find(val);

    if (curNode) {
      curNode.val = val;
    } else {
      throw `${val}节点不存在`
    }
  }

  // 打印链表
  print() {
    const list = [];
    let curNode = this.head;
    list.push(curNode.val);

    while (curNode.next) {
      curNode = curNode.next;
      list.push(curNode.val);
    }

    console.log(list);
  }

  // 反向打印链表
  printReverse() {
    const list = [];
    let curNode = this.head;
    list.unshift(curNode.val);

    while (curNode.next) {
      curNode = curNode.next;
      list.unshift(curNode.val);
    }

    console.log(list);
  }
}

// 测试

let text = new LinkList(3);

text.add(5);
text.add(8);
text.add(11);
text.add(2);
text.add(7);

text.print();

text.add(100)
text.print();
text.insert(11, 3000)
text.print()
